package com.hxkj.service.impl;


import com.hxkj.client.service.ChannelServiceClient;
import com.hxkj.dao.NavigationDao;
import com.hxkj.domain.enums.NavigationExceptionEnum;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.Navigation;
import com.hxkj.domain.po.NavigationTree;
import com.hxkj.service.NavigationService;
import com.hxkj.utils.StrSliptUtils;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 导航栏Service实现类
 * <p>
 * Created by chenfangzhou on 2018/6/7.
 */
@Service
@Slf4j
public class NavigationServiceImpl implements NavigationService {

    @Autowired
    private NavigationDao navigationDao;

    /**
     * 保存导航栏
     *
     * @param navigation
     * @return
     * @throws Exception
     */
    @Override
    public ResultDataStruct saveNavigation(Navigation navigation) throws Exception {
        ResultDataStruct resultDataStruct = new ResultDataStruct();
        //根据导航栏名称判断是否重复
        Navigation newNavigation = new Navigation();
        newNavigation.setNavigationName(navigation.getNavigationName());
        newNavigation.setSiteId(navigation.getSiteId());
        newNavigation.setDelTag(0);
        try {
            if (navigationDao.get(newNavigation).size() > 0) {
                resultDataStruct.setCode(NavigationExceptionEnum.NAVIGATION_EXIST_ALREADY.getCode());
                return resultDataStruct;
            } else {
                navigation.setCreateTime(System.currentTimeMillis());
                navigation.setUpdateTime(System.currentTimeMillis());
                // 增加后返回增加的对象
                int i = navigationDao.saveNavigation(navigation);
                resultDataStruct.setData(navigation);
                resultDataStruct.setCode(200);
                return resultDataStruct;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultDataStruct.setCode(NavigationExceptionEnum.NAVIGATION_SAVE_ERROR.getCode());
        }
        return resultDataStruct;
    }

    /**
     * 获取单条导航栏
     *
     * @param navigation
     * @return
     * @throws Exception
     */
    @Override
    public ResultDataStruct<Navigation> getNavigation(Navigation navigation) throws Exception {

        ResultDataStruct<Navigation> resultDataStruct = new ResultDataStruct<>();
        try {
            Navigation newNavigation = navigationDao.get(navigation.getNavigationId());

            if (newNavigation == null) {
                resultDataStruct.setCode(NavigationExceptionEnum.NAVIGATION_IS_NULL.getCode());
                return resultDataStruct;
            } else {
                if (newNavigation.getDelTag() == 1) {
                    resultDataStruct.setCode(NavigationExceptionEnum.NAVIGATION_IS_NULL.getCode());
                    return resultDataStruct;
                } else {
                    resultDataStruct.setCode(200);
                    resultDataStruct.setData(newNavigation);
                    return resultDataStruct;
                }
            }
        } catch (Exception e) {
            resultDataStruct.setCode(NavigationExceptionEnum.NAVIGATION_QUERY_ERROR.getCode());
            e.printStackTrace();
            return resultDataStruct;
        }
    }


    /**
     * 获取导航栏列表
     *
     * @param navigation
     * @return
     * @throws Exception
     */
    @Override
    public ResultDataStruct<List<NavigationTree>> getNavigationList(Navigation navigation) throws Exception {
        ResultDataStruct<List<NavigationTree>> result = new ResultDataStruct();
        String keyword = navigation.getKeyword();
        List<NavigationTree> trees = new ArrayList<>();
        try {
            // 模糊查询
            if (StringUtils.isBlank(keyword)) {
                List<NavigationTree> navigationTrees = getChild(-1L, navigation);
                result.setCode(200);
                result.setData(navigationTrees);
                return result;
            } else {
                // 最顶级的导航栏
                navigation.setDelTag(0);
                List<Navigation> navigations = navigationDao.get(navigation);
                // 利用set集合去重
                Set<Navigation> navigationSet = new HashSet<>();
                for (Navigation nav : navigations) {
                    getParent(nav.getNavigationId());
                    Navigation na = navigation1;
                    navigationSet.add(na);
                }
                for (Navigation na : navigationSet) {
                    NavigationTree navigationTree = new NavigationTree();
                    navigationTree.setNavigationId(na.getNavigationId());
                    navigationTree.setParentNavigationId(na.getParentNavigationId());
                    navigationTree.setNavigationName(na.getNavigationName());
                    navigationTree.setCreateTime(na.getCreateTime());
                    navigationTree.setUpdateTime(na.getUpdateTime());
                    navigationTree.setDelTag(na.getDelTag());
                    navigationTree.setIsEnable(na.getIsEnable());
                    navigationTree.setNavigationUrl(na.getNavigationUrl());
                    navigationTree.setSortNumber(na.getSortNumber());
                    navigationTree.setSiteId(na.getSiteId());
                    navigationTree.setTempletId(na.getTempletId());
                    navigationTree.setManuscriptPath(na.getManuscriptPath());
                    navigationTree.setOpenType(na.getOpenType());
                    navigationTree.setWebUrl(na.getWebUrl());
                    navigationTree.setArticleId(na.getArticleId());
                    navigationTree.setComment(na.getComment());
                    navigationTree.setChannelId(na.getChannelId());
                    navigationTree.setNavigationImg(na.getNavigationImg());
                    navigationTree.setChildren(getChild(na.getNavigationId(), na));
                    trees.add(navigationTree);
                }
                result.setCode(200);
                result.setData(trees);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    // 定义一个全局变量存值
    private Navigation navigation1 = new Navigation();

    // 获取导航栏的最顶级父导航栏
    private Navigation getParent(Long id) {
        navigation1 = navigationDao.get(id);
        if (navigation1.getParentNavigationId() != -1) {
            getParent(navigation1.getParentNavigationId());
        }
        return navigation1;
    }

    private List<NavigationTree> getChild(Long id, Navigation nav) {
        List<NavigationTree> trees = new ArrayList<>();
        Navigation navigation = new Navigation();
        navigation.setParentNavigationId(id);
        navigation.setDelTag(0);
        navigation.setSiteId(nav == null ? null : nav.getSiteId());
        navigation.setIsEnable(nav == null ? null : (nav.getIsEnable() == null ? null : nav.getIsEnable()));
        // 获取所有子类
        List<Navigation> navigationList = navigationDao.get(navigation);
        if (navigationList != null && navigationList.size() > 0) {

            for (Navigation root : navigationList) {
                NavigationTree navigationTree = new NavigationTree();
                navigationTree.setNavigationId(root.getNavigationId());
                navigationTree.setParentNavigationId(root.getParentNavigationId());
                navigationTree.setNavigationName(root.getNavigationName());
                navigationTree.setCreateTime(root.getCreateTime());
                navigationTree.setUpdateTime(root.getUpdateTime());
                navigationTree.setDelTag(root.getDelTag());
                navigationTree.setIsEnable(root.getIsEnable());
                navigationTree.setNavigationUrl(root.getNavigationUrl());
                navigationTree.setSortNumber(root.getSortNumber());
                navigationTree.setSiteId(root.getSiteId());
                navigationTree.setTempletId(root.getTempletId());
                navigationTree.setManuscriptPath(root.getManuscriptPath());
                navigationTree.setOpenType(root.getOpenType());
                navigationTree.setWebUrl(root.getWebUrl());
                navigationTree.setArticleId(root.getArticleId());
                navigationTree.setComment(root.getComment());
                navigationTree.setChannelId(root.getChannelId());
                navigationTree.setNavigationImg(root.getNavigationImg());
                navigationTree.setChildren(getChild(root.getNavigationId(), nav));
                trees.add(navigationTree);
            }
        }
        return trees;
    }

    @Override
    public ResultMessageStruct updateNavigation(Navigation navigation) {
        ResultMessageStruct result = new ResultMessageStruct();
        try {
            if (StringUtils.isNoneBlank(navigation.getNavigationName())) {
                // 判断导航栏是否已经存在，如果存在则不允许重复添加
                Navigation newNavigation = navigationDao.selectNavigationName(navigation);
                if (newNavigation != null) {
                    result.setCode(NavigationExceptionEnum.NAVIGATION_EXIST_ALREADY.getCode());
                    return result;
                }
            }
            int i = navigationDao.update(navigation);
            result.setCode(i > 0 ? 200 : NavigationExceptionEnum.NAVIGATION_UPDATE_ERROR.getCode());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(NavigationExceptionEnum.NAVIGATION_UPDATE_ERROR.getCode());
            return result;
        }
    }


    /**
     * 删除导航栏,可批量删除,也可单条删除
     *
     * @param navigation
     * @return
     */
    @Override
    public ResultMessageStruct deleteNavigation(Navigation navigation) {
        ResultMessageStruct resultMessageStruct = new ResultDataStruct<>();
        try {
            if (StringUtils.isNoneBlank(navigation.getNavigationIds())) {
                String[] str = StrSliptUtils.sliptArray(navigation.getNavigationIds());
                for (int i = 0; i < str.length; i++) {
                    resultMessageStruct = validateDelete(Long.valueOf(str[i]));
                    if (resultMessageStruct.getCode() == 200) {
                        navigationDao.delete(Long.valueOf(str[i]));
                    } else {
                        return resultMessageStruct;
                    }
                }
            } else {// 删除单条
                resultMessageStruct = validateDelete(navigation.getNavigationId());
                if (resultMessageStruct.getCode() == 200) {
                    navigationDao.delete(navigation.getNavigationId());
                } else {
                    return resultMessageStruct;
                }
            }
            resultMessageStruct.setCode(200);
            return resultMessageStruct;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resultMessageStruct.setCode(NavigationExceptionEnum.NAVIGATION_DELETE_ERROR.getCode());
            return resultMessageStruct;
        }
    }


    // 自建私有方法,判断导航栏是否能删除
    private ResultMessageStruct validateDelete(Long navigationId) {
        ResultMessageStruct result = new ResultMessageStruct();

        // 获取需要删除的栏目对象
        Navigation obj = navigationDao.get(navigationId);

        // 判断该导航栏下是否有子栏目
        Navigation newNavigation = new Navigation();
        newNavigation.setParentNavigationId(navigationId);
        if (navigationDao.get(newNavigation).size() > 0) {

            // 该导航栏下有子类
            result.setCode(NavigationExceptionEnum.NAVIGATION_HAS_CHILD.getCode());
            return result;
        }
        result.setCode(200);
        return result;

    }

    /**
     * 导航栏排序
     *
     * @param map 导航栏信息
     * @return
     * @throws Exception
     */
    @Override
    public ResultMessageStruct modifyOrderId(Map<String, Object> map) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        Navigation navigation = new Navigation();
        String[] id = map.get("ids").toString().split(",");
        navigation.setSiteId(Long.parseLong(map.get("siteId").toString()));
        for (int i = 0; i < id.length; i++) {
            try {
                navigation.setNavigationId(Long.parseLong(id[i]));
                navigation.setSortNumber((byte) i);
                int j = navigationDao.update(navigation);
                result.setCode(j == 1 ? 200 : NavigationExceptionEnum.NAVIGATION_UPDATE_ERROR.getCode());
                if (200 != result.getCode()) {
                    return result;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                result.setCode(NavigationExceptionEnum.NAVIGATION_UPDATE_ERROR.getCode());
            }
        }
        return result;
    }

    /**
     * 导航栏类表,不带树结构
     *
     * @param navigation
     * @return
     */
    @Override
    public ResultDataStruct<List<Navigation>> getList(Navigation navigation) {
        ResultDataStruct<List<Navigation>> result = new ResultDataStruct<>();
        try {
            result.setData(navigationDao.get(navigation));
            result.setCode(200);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }


    /**
     * 根据主键删除
     *
     * @param navigationId
     * @return
     */
    @Override
    public ResultMessageStruct deleteByPrimarykey(Long navigationId) {
        ResultMessageStruct result = new ResultMessageStruct();
        try {
            navigationDao.delete(navigationId);
            result.setCode(200);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 保存导航栏地址(分类的静态页地址)
     *
     * @param column
     * @return
     * @throws Exception
     */
    @Override
    public ResultMessageStruct saveColumnToNavigation(Column column) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        Navigation navigation = new Navigation();
        try {
            navigation.setSiteId(column.getSiteId());
            navigation.setNavigationUrl(column.getManuscriptPath());
            int count = navigationDao.selectNavigationByColumn(navigation);
            //导航栏没有该链接则，新增该分类链接
            if (count == 0) {
                navigation.setNavigationName(column.getColumnName());
                navigation.setDelTag(0);
                navigation.setIsEnable(0);
                navigationDao.saveNavigation(navigation);
            }
            result.setCode(200);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
